﻿using System;
using System.Reflection;
using System.Web.UI;

namespace TemplateLibraryConnector.UI
{
    [AttributeUsage(AttributeTargets.Property)]
    public class PersistToViewState : Attribute
    {
    }

    public class ViewStateHandler
    {
        public static void SaveViewState(Object currentObject, StateBag viewState)
        {
            PropertyInfo[] properties = currentObject.GetType().GetProperties();
            foreach (PropertyInfo property in properties)
            {
                object[] attributes = property.GetCustomAttributes(typeof (PersistToViewState), true);
                if (attributes.Length > 0)
                    viewState[property.Name] = property.GetValue(currentObject, null);
            }
        }

        public static void LoadViewState(object currentObject, StateBag viewState)
        {
            PropertyInfo[] properties = currentObject.GetType().GetProperties();
            foreach (PropertyInfo property in properties)
            {
                object[] attributes = property.GetCustomAttributes(typeof (PersistToViewState), true);
                if (attributes.Length > 0)
                {
                    if (viewState[property.Name] != null)
                        property.SetValue(currentObject, viewState[property.Name], null);
                }
            }
        }
    }
}